<?php if (!defined('BASEPATH')) {
	exit('No direct script access allowed');
}

class Sample extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct() {
		parent::__construct();
		$this->load->model('wus');
		$this->load->model('map_functions_model');
		$this->load->library('variable');
		$this->load->helper('download');
	}

	public function index() {
		//$this->wus->call_acct_chg();
		//$this->session->set_userdata(array('logged_in' => 1));
		$this->check_login();
	}

	public function check_login() {
		if ($this->session->userdata('logged_in') == 0 || $this->session->userdata('logged_in') == null) {
			$this->login();
		} else {
			$this->main();
		}
	}

	// public function main() {
	// 	$this->load->view('layouts/header', $this->variable->load_data("UMS | HOME"));

	// 	$this->load->view('body/content',array(
	// 			'zone1' => $this->map_functions_model->getzoning('Zone1'),
	// 		));
	// 	$this->load->view('layouts/footer');
	// }

	public function main() {
		//billing
		$current = $this->wus->get_status(0,$this->session->userdata('company_id'));
		$ym="";
		if($current != null){
			if((date('m',strtotime($current[0]->yearMonth))-1) == 0){
			$ym = (date('Y',strtotime($current[0]->yearMonth))-1).'-'.'12';	
			}else{
				$ym = date('Y',strtotime($current[0]->yearMonth)).'-'.(date('m',strtotime($current[0]->yearMonth))-1);	
			}
		}
		
		
		$pm = date('Y-m',strtotime($ym));

		//collection
		$curCol = $this->wus->get_status_col(0,$this->session->userdata('company_id'));
		$ymC="";
		if($curCol != null){
			if((date('m',strtotime($curCol[0]->yearMonth))-1) == 0){
				$ymC = (date('Y',strtotime($curCol[0]->yearMonth))-1).'-'.'12';	
			}else{
				$ymC = date('Y',strtotime($curCol[0]->yearMonth)).'-'.(date('m',strtotime($curCol[0]->yearMonth))-1);	
			}
		}
		$pmC = date('Y-m',strtotime($ymC));

		//half year revenue
		
			$pmHY = "";
		if($curCol != null){
				$mon = intval(date('m',strtotime($curCol[0]->yearMonth)));
				$yer = intval(date('Y',strtotime($curCol[0]->yearMonth)));
				if($mon-6 < 0){
					$mon = 13-(6-$mon);
					$yer = $yer - 1;
				}else{
					$mon = $mon-5;
				}
				if($mon < 10){ 
					$pmHY = $yer.'-0'.$mon;
				}else{
					$pmHY = $yer.'-'.$mon;
				}
		}
		$this->load->view('layouts/header', $this->variable->load_data("WUMS | HOME",0,0,0,''));

		$this->load->view('body/content',array(
				'bill_data' => $current,
				'coll_data' => $curCol,
				'prv_bills' => $this->wus->get_status($pm,$this->session->userdata('company_id')),
				'prv_colls'	=> $this->wus->get_status_col($pmC,$this->session->userdata('company_id')),
				'hyear_rev' => $this->wus->get_HY_rev($pmHY,$this->session->userdata('company_id')),
				'cyear_rev' => $this->wus->get_HY_col($pmHY,$this->session->userdata('company_id')),
				'ly'	=> $pmHY
			));
		$this->load->view('layouts/footer');
	}
	

	public function login() {
		//$this->wus->call_acct_chg();
		$this->load->view('login');

	}

	public function req_login() {
		$data = array(
			'user_name' => filter_var($this->input->post('user_name'), FILTER_SANITIZE_STRING),
			'password' => filter_var($this->input->post('password'), FILTER_SANITIZE_STRING),
		);

		$q = $this->wus->login($data);
		//var_dump($q);
		if (!empty($q)) {
			foreach ($q as $key) {
				if (password_verify($data['password'], $key->pwd) == true) {
					
					$this->session->set_userdata(array(
						'logged_in'    => 1,
						'role_id'      => $key->role_id,
						'username'     => $key->user_name,
						'user_id'      => $key->user_id,
						'company_id'   => $key->company_id,
						'comp_name'    => $key->company_name,
						'f_name'       => $key->first_name,
						'l_name'       => $key->last_name,
						'enable_flag'  => $key->enable_flag,
						'bu_id'        => $key->bu_id,
						'bu_name'      => $key->bu_name
					));
					echo json_encode(array('msg' => 'success'));
				} else {
					echo json_encode(array('msg' => 'invalid username/password.'));
				}
			}
		} else {
			$q = $this->wus->login_cust($data);
			if(!empty($q)){
				foreach($q as $key) {
					if (password_verify($data['password'], $key->password) == true) {
						$s = $this->wus->get_details($key->account_num);
						$this->session->set_userdata(array(
						'logged_in' => 1));
						echo json_encode(array('msg' => 'success'));
						//echo json_encode(array('msg' => 'cust_home'));
					}else{
						echo json_encode(array('msg' => 'invalid username/password.'));
					}
				}
			}else{
				echo json_encode(array('msg' => 'invalid username/password.'));
			}
		}
	}
	public function cust_homepage(){
		var_dump($this->session->all_userdata());
		/*$this->load->view('layouts/header_cust', $this->variable->load_data("UMS | HOME"));
		$this->load->view('body/content');
		$this->load->view('layouts/footer_cust');*/
	}

	public function logout() {
		$this->session->sess_destroy();
		$this->index();
	}

	public function reset_pass(){
		if ($this->session->userdata('logged_in') == 0 || $this->session->userdata('logged_in') == null) {
			$this->login();
		}
		$data = array(
			'pwd' => password_hash($this->input->post('new_pass'),PASSWORD_DEFAULT)
		   ,'updated_by' => $this->session->userdata('user_id')
		   ,'update_date' => date('Y-m-d H:i:S'));
		$this->wus->resetpass($data);
	}

	public function validate_emails(){
		if($this->wus->checkmail($_GET['email'])){
			echo 'false';
		}else{
			echo 'true';
		}
	}
	public function validate_email(){
		if($this->wus->checkmail($_POST['email'])){
			echo json_encode(true);
		}else{
			if($this->wus->check_ifexist_an($_POST['email'])){
				echo json_encode(true);
			}else{
				echo json_encode($_POST['email'].' not exists.');
			}
		}
	}

	public function forget_pwd(){
		$email = $this->input->post('email');
		$pass = random_string('alnum', 8);
		$msg = 'Dear Customer, </br> Your New Password is now <b>'.$pass.'</b>. </br> Please change your password to secure your account. Thank You.';
		$subj = 'Reset Password';
		$data = array(
			':p_email' => $email,
			':p_pwd' => password_hash($pass,PASSWORD_DEFAULT)
			);
		$q = $this->wus->forget($data);
		foreach($q as $key){
			if($key->error == 1){
				echo json_encode($q);
			}else{
				//echo json_encode($q);
				$this->send_email($email,$subj,$msg);
			}
		}
	}

	function gee(){
		echo random_string('alnum', 8);
	}
	public function signup(){
		$data = array(
			':d_password'     => password_hash($this->input->post('password'),PASSWORD_DEFAULT),
			':d_email'        => filter_var($this->input->post('email'), FILTER_SANITIZE_STRING),
			':d_code'	      => random_string('alnum', 20),
			':d_account_num'  => $this->input->post('account_num')
		);

		echo json_encode($this->wus->register($data));
	}

	public function send_email($email,$subj,$msg){
		$config['protocol'] = "smtp";
		$config['smtp_host'] = "ssl://smtp.gmail.com";
		$config['mailpath'] = "assets/tmp";
		$config['smtp_port'] = 465;
		$config['smtp_user'] = "tetsuyakuroko101@gmail.com";
		$config['smtp_pass'] = "dwuydqsvumopnxdk";
		$config['smtp_timeout'] = 5;
		$config['charset'] = "utf-8";
		$config['mailtype'] = "html";
		$config['newline'] = "\r\n";
		$config['crlf'] = "\n";
		$this->email->initialize($config);

		$this->email->from('Kyogojo Water Bill','@no_reply_please');
		$this->email->to($email);
		$this->email->subject($subj);
		$this->email->message($msg);
		if ($this->email->send()) {
			echo json_encode(array('msg' => 'success'));
		} else {
			echo json_encode(array('msg' => 'fail'));
			//show_error($this->email->print_debugger());
		}
	}

	public function if_exist_email(){

	}

	public function if_exist_uname(){

	}

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */